# -*- coding: utf-8 -*-
"""
Created on Tue Aug 14 11:16:05 2018

@author: jiujiujiu
"""

import requests
import json
import time
from WriteData import writedata
from Tk import genearteMD5
from cs import day


# 获取页面
def postHTMLText(url, data):
    header = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'}
    try:
        r = requests.post(url, timeout=30, headers=header, data=data)
        r.raise_for_status()  # 如果状态不是200, 引发HTTPError异常
        r.encoding = r.apparent_encoding
        html = r.text
        return html

    except:
        return None


def get_date_count(url, data):
    html = postHTMLText(url, data)
    if not html:
        return 0
    #    h = eval(html)
    d = json.loads(html)
    #    print(type(d))
    datas = d['data']
    #    print(datas)
    count = len(datas)
    #    print(count)
    return count


def get_data(url, data):
    dates = []
    html = postHTMLText(url, data)
    if not html:
        return None
    #    h = eval(html)
    d = json.loads(html)
    data = d['data']
    for date in data:
        date = time.strftime("%Y-%m-%d %X", time.localtime(int(date['ctime'])))[:10]
        dates.append(date)
    return dates


def count_process_two():  # 只能获取今天快讯
    url = 'http://www.chainpow.com/index.php?g=LBFinance&m=Pc&a=initDispatchArticle'
    data = {
        'offset': '0'
    }
    count = get_date_count(url, data)
    return count


def count_process_one():  # 资讯-最新
    d1 = 0
    d2 = 0
    d3 = 0
    d4 = 0
    a = 0
    while 1:
        s = d1 + d2 + d3
        url = 'http://www.chainpow.com/index.php?g=LBFinance&m=Pc&a=initArticleByClassId'
        data = {
            'classid': '12',
            'offset': a}

        datelist = get_data(url, data)
        if not datelist:
            break
        for date in datelist:
            s = day(date[:10])
            if s == 0:
                d1 += 1
            elif s == 1:
                d2 += 1
            elif s == 2:
                d3 += 1
            else:
                d4 += 1
        a += 1
        print('----链豹财经资讯第{}页获取中----'.format(a))
        if d4 > 0:
            break
    return (d1, d2, d3)


def main():
    u = '链豹财经'
    t1 = count_process_one()
    t2 = count_process_two()
    tk = genearteMD5(u)
    D = {tk: {"name": u, "today": t1[0] + t2, "yesterday": t1[1], "frontday": t1[2]}}
    writedata(D)
    return D


if __name__ == '__main__':
    print(main())
